let keywords = document.getElementById("keywords");
let send = document.getElementById("send");
let prev = document.getElementById("prev");
let next = document.getElementById("next");
let player = document.getElementById("player");
let tbody = document.querySelector("table > tbody");
let offsetNumber = 0;//自定义偏移量

//封装
function render(offsetNumber) {
  // 检测搜索框内是否有关键字，有则进行搜索并渲染，无则不渲染
  if (keywords.value) {
    //渲染前先清空tbody的内容，避免重复
    tbody.innerHTML = "";
    //请求数据
    ajax("get", `https://music.0melon0.cn/search?keywords=${keywords.value}&offset=${offsetNumber}&limit=${10}`, function (res) {
      // console.log(keywords.value);
      // console.log(res.result.songs);
      res.result.songs.forEach(function (item) {
        tbody.innerHTML += `
    <tr id=${item.id}>
    <td>${item.name}</td>
    <td>${item.artists[0].name}</td>
    <td>${item.album.name}</td>
    <td>${moment(item.duration).format('mm:ss')}</td>  
</tr> `
      })

      let allTr = document.querySelectorAll("tr");
      allTr.forEach(function (item) {
        item.addEventListener("click", function () {
          // console.log(item);
          //根据tr的id属性值获取对于歌曲在接口中的id值
          ajax("get", `https://music.0melon0.cn/song/url?id=${item.id}`, function (res) {
            // console.log(res);
            //把接口中的相应id值的歌曲链接放到播放器中
            player.setAttribute("src", res.data[0].url);
            // player.src = res.data[0].url;
          })
        })
      })
    })
  }
}

// 搜索
send.addEventListener("click", function () {
  offsetNumber = 0;
  render(offsetNumber);
})

//上一页
prev.addEventListener("click", function () {
  //当offsetNumber小于0时，重新赋值为0
  (offsetNumber < 0) && (offsetNumber = 0)
  if (offsetNumber > 0) {
    //向上一页偏移10首歌曲
    offsetNumber -= 10;

    render(offsetNumber);
  }
})

//下一页
next.addEventListener("click", function () {
  // (offsetNumber < 0) && (offsetNumber = 0)
  if (offsetNumber >= 0) {
    //向下一页偏移10首歌曲
    offsetNumber += 10;

    render(offsetNumber);
  }
})

